<template lang="pug">
  el-form-item(ref="formItem" label-width="0px" :prop="config.propertyName"  :rules="rules")
    requiredLabel(:required="required" :label="config.label")
    .show-date-value
      template(v-if="config.dateType.indexOf('range')<0")
        van-field(v-model="dateValue" @click="popupOpen(dateValue,'one')" :placeholder="readonly?'':config.placeholder1" readonly)
      .show-date-value-range(v-if="config.dateType.indexOf('range')>-1")
        van-field(v-model="dateValue[0]" @click="popupOpen(dateValue[0],'twoFirst')" :placeholder="readonly?'':config.placeholder1" readonly)
        span 至
        van-field(v-model="dateValue[1]" @click="popupOpen(dateValue[1],'twoEnd')" :placeholder="readonly?'':config.placeholder2" readonly)
      i.date-icon(v-if="deleteIconShow" class="el-icon-error" @click.stop="deleteValue")
      //- svg-icon.date-icon(v-if="!readonly&&dateValue" icon-class="delete" @click.stop="deleteValue")
    van-popup(v-model="popupShow" position="bottom" :lazy-render="false")
      date-picker(v-if="config.dateType==='date'||!config.dateType||config.dateType==='daterange' " ref='date' :editor="editor" :config="config"  v-model="value" :readonly="readonly" @popupClose="popupClose")
      datetime-picker(v-if="config.dateType==='datetime'||config.dateType==='datetimerange' " ref='date' :editor="editor" :config="config"  v-model="value" :readonly="readonly" @popupClose="popupClose")
      time-picker(v-if="config.dateType==='time'" ref='date' :editor="editor" :config="config"  v-model="value" :readonly="readonly" @popupClose="popupClose")
      yearmonth-picker(v-if="config.dateType==='yearmonth'" ref='date' :editor="editor" :config="config"  v-model="value" :readonly="readonly" @popupClose="popupClose")

</template>
<script>
import inputCommon from '../../../../mixin/inputCommon'
import requiredLabel from '../../../../components/requiredLabel'
import datePicker from './datePicker'
import datetimePicker from './datetimePicker'
import timePicker from './timePicker'
import yearmonthPicker from './yearmonthPicker'
import { addZero } from '../../../../../../../../common/utils/validate'
import _ from 'lodash'

export default {
  name: 'dateRender',
  components: { datePicker, timePicker, datetimePicker, requiredLabel, yearmonthPicker },
  mixins: [inputCommon],
  props: ['config', 'editor'],
  inject: ['rootForm'],
  data() {
    return {
      popupShow: false,
      value: undefined,
      flag: undefined, // one:单个时间；twoFirst:范围的开始时间；twoSecond：范围的结束时间
      default: this.config.dateType.indexOf('range') > -1 ? [] : '',
      dateValue: this.config.dateType.indexOf('range') > -1 ? [] : '',
      effectiveValue: ''
    }
  },
  computed: {
    deleteIconShow() {
      if (!this.readonly && this.config.dateType.indexOf('range') > -1 && this.dateValue && this.dateValue.length) {
        return true
      } else if (!this.readonly && this.config.dateType.indexOf('range') === -1 && this.dateValue) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    deleteValue() {
      this.dateValue = this.default
      this.value = undefined
      this.$refs.formItem.$emit('el.form.change', this.default)
    },
    popupOpen(value, flag) {
      if (!this.readonly) {
        this.value = value
        this.flag = flag
        this.popupShow = true
        let pick = this.$refs.date && this.$refs.date.$refs.pick
        // 回显值
        if (value && value.indexOf('-') > -1) {
          let date = new Date(value)
          pick.$children[0].setValues([date.getFullYear() + '年', addZero(date.getMonth() + 1) + '月', addZero(date.getDate()) + '日', addZero(date.getHours()), addZero(date.getMinutes())])
        } else if (value && value.indexOf('-') === -1) {
          let date = value.split(':')
          pick.$children[0].setValues([date[0], date[1]])
        } else if (!value && this.config.dateType === 'time') {
          let date = new Date()
          pick.$children[0].setValues([addZero(date.getHours()), addZero(date.getMinutes())])
        } else if (!value && (this.config.dateType.indexOf('date') > -1 || this.config.dateType === 'yearmonth')) {
          let date = new Date()
          pick.$children[0].setValues([date.getFullYear() + '年', addZero(date.getMonth() + 1) + '月', addZero(date.getDate()) + '日', addZero(date.getHours()), addZero(date.getMinutes())])
        }
      }
    },
    popupClose(value) {
      this.popupShow = false
      if (value) {
        if (this.flag === 'one') {
          this.dateValue = value
          // this.$set(this.rootForm.properties, this.config.propertyName, value)
        } else if (this.flag === 'twoFirst') {
          let lastTime = this.dateValue[1]
          if (!lastTime || value > lastTime) {
            lastTime = value
          }
          this.dateValue = [value, lastTime]
          // this.$set(this.rootForm.properties, this.config.propertyName, [value, lastTime])
        } else if (this.flag === 'twoEnd') {
          let firstTime = this.dateValue[0]
          if (!firstTime) {
            firstTime = value
          } else if (firstTime > value) {
            value = firstTime
          }
          this.dateValue = [firstTime, value]
          // this.$set(this.rootForm.properties, this.config.propertyName, [firstTime, value])
        }
        this.$refs.formItem.$emit('el.form.change', this.dateValue)
      }
    },
    commit() {
      this.effectiveValue = this.dateValue
    }
  },
  beforeDestroy() {
    if (this.config.type === 'param') {
      this.observer.removeParamsGetter(this.paramsGetter)
    } else if (this.config.type === 'normal') {
      this.observer.removeFilter(this.filterFn)
    }
  },
  created() {
    this.observer = this.rootForm.dataInterfaceObserverManage.get(this.config.dataInterfaceId)
    if (this.config.type === 'param') {
      if (this.config.dateType.indexOf('range') === -1) {
        this.paramsGetter = () => {
          let obj = {}
          let params = this.config.paramName.split(',')
          params.forEach(one => {
            obj[one] = this.effectiveValue
          })
          return obj
        }
        this.observer.addParamsGetter(this.paramsGetter)
      } else {
        this.paramsGetter = () => {
          let obj = {}
          let paramsStart = this.config.paramNameStart.split(',')
          paramsStart.forEach(one => {
            obj[one] = this.effectiveValue ? this.effectiveValue[0] : ''
          })
          let paramsEnd = this.config.paramNameEnd.split(',')
          paramsEnd.forEach(one => {
            obj[one] = this.effectiveValue ? this.effectiveValue[1] : ''
          })
          return obj
        }
        this.observer.addParamsGetter(this.paramsGetter)
      }
    } else if (this.config.type === 'normal') {
      let filter = (data, filterKeyList) => {
        return data.filter(one => filterKeyList.some(key => {
          if (this.config.dateType.indexOf('range') === -1) {
            let v = _.at(one, key)[0]
            if (!v) {
              return false
            }
            return v.indexOf(this.effectiveValue) > -1
          } else {
            let v = _.at(one, key)[0]
            if (!v) {
              return false
            }
            return this.effectiveValue[0] <= v && this.effectiveValue[1] >= v
          }
        }))
      }

      this.filterFn = (data) => {
        let filterKeyList = this.config.filterKeys.split(',').map(one => one.trim())
        if (this.config.listKey) {
          let list = _.at(data, this.config.listKey)[0]
          let filteredList = filter(list, filterKeyList)
          _.update(data, this.config.listKey, () => filteredList)
          return data
        }
        return filter(data, filterKeyList)
      }
      this.observer.addFilter(this.filterFn)
    }
  }
}
</script>
